package store

import (
	baseStore "gitee.com/zaiqiang231/go-base-app/base_app/store"
	"gitee.com/zaiqiang231/zcamp-service-user/app/model"
	"gorm.io/gorm"
)

func GetUserStore() *UserStore {
	return &UserStore{
		db: baseStore.GetDataStore().DB,
	}
}

type UserStore struct {
	db *gorm.DB
}

func (u *UserStore) GetByName(username string) (*model.User, error) {
	user := &model.User{}
	err := u.db.
		Where("name = ?", username).
		First(&user).Error
	if err != nil {
		return nil, err
	}
	return user, nil
}

func (u *UserStore) GetByRegisterPhone(phone string) (*model.User, error) {
	user := &model.User{}
	err := u.db.
		Where("register_phone = ?", phone).
		First(&user).Error
	if err != nil {
		return nil, err
	}
	return user, nil
}

func (u *UserStore) GetByUid(uid int64) (*model.UserMore, error) {
	user := &model.User{}
	err := u.db.
		Where("uid = ?", uid).
		First(&user).Error
	if err != nil {
		return nil, err
	}

	var userAdmin model.UserAdmin
	isPostAdmin := false
	tmperr := u.db.
		Where("uid = ?", uid).
		First(&userAdmin).Error
	if tmperr == nil {
		isPostAdmin = userAdmin.PostAdmin == 1
	}

	return &model.UserMore{
		User:        *user,
		IsPostAdmin: isPostAdmin,
	}, nil
}

func (u *UserStore) GetByUids(uids []int64) ([]model.User, error) {
	users := make([]model.User, 0)
	err := u.db.
		Where("uid in (?)", uids).
		Find(&users).Error
	if err != nil {
		return nil, err
	}
	return users, nil
}
